'use strict';

const { resolve } = require('path');

// 是否为对象
function isObject(data) {
  return Object.prototype.toString.call(data) === '[object Object]'
}

// 是否为数组
function isArray(data) {
  return Array.isArray(data)
}

// 下载package包的时候 的动画效果
function spinnerStart(msg) {
  const Spinner = require('cli-spinner').Spinner

  const spinner = new Spinner(msg + '%s');
  spinner.setSpinnerString('|/-\\');
  spinner.start();// 动画开始
  return spinner
}

function sleep(timeout) {
  return Promise.resolve(() => setTimeout(() => {}, timeout))
}

// 兼容windows
function execSpawn(command, args, options) {
  const win32 = process.platform === 'win32'

  const cmd = win32 ? 'cmd' : command
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args
  // console.log(1111, cmd, cmdArgs , options)
  // child_process/node子进程
  return require ('child_process').spawn(cmd, cmdArgs, options || {})
}

function execAsync(command, args, option) {
  return new Promise((resolve, reject) => {
    const child = execSpawn(command, args, option)
    child.on('error', e => {
      // 失败
      reject(e)
    })
    // 成功
    child.on('exit', c => {
      // c === 0 执行成功
      resolve(c)
    })
  })
}

module.exports = {
  isObject,
  isArray,
  spinnerStart,
  sleep,
  execSpawn,
  execAsync
}
